package com.znjc.web.controller.device;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.znjc.common.annotation.Log;
import com.znjc.common.core.controller.BaseController;
import com.znjc.common.core.domain.AjaxResult;
import com.znjc.common.core.domain.entity.SysDept;
import com.znjc.common.core.page.TableDataInfo;
import com.znjc.common.enums.BusinessType;
import com.znjc.common.utils.StringUtils;
import com.znjc.common.utils.poi.ExcelUtil;
import com.znjc.device.domain.DeviceDevice;
import com.znjc.device.domain.DeviceType;
import com.znjc.device.domain.IotDataResRule;
import com.znjc.device.service.IDeviceDeviceService;
import com.znjc.device.service.IDeviceRuleRefService;
import com.znjc.device.service.IDeviceTypeService;
import com.znjc.device.service.IIotDataResRuleService;
import com.znjc.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 【规则】Controller
 *
 * @author zengpc
 * @date 2023-12-04
 */
@RestController
@RequestMapping("/device/rule")
public class IotDataResRuleController extends BaseController {
    @Autowired
    private IIotDataResRuleService iotDataResRuleService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IDeviceRuleRefService deviceRuleRefService;
    @Autowired
    private IDeviceTypeService deviceTypeService;
    @Autowired
    private IDeviceDeviceService deviceDeviceService;
    /**
     * 查询解析规则管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:rule:list')")
    @GetMapping("/list")
    public TableDataInfo list(IotDataResRule iotDataResRule) {
        startPage();
        LambdaQueryWrapper<IotDataResRule> wrapper = getWrapper(iotDataResRule);
        List<IotDataResRule> list = iotDataResRuleService.list(wrapper);
        return getDataTable(packList(list));
    }

    /**
     * 导出解析规则管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:rule:export')")
    @Log(title = "解析规则管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IotDataResRule iotDataResRule) {
        LambdaQueryWrapper<IotDataResRule> wrapper = getWrapper(iotDataResRule);
        List<IotDataResRule> list = iotDataResRuleService.list(wrapper);
        ExcelUtil<IotDataResRule> util = new ExcelUtil<IotDataResRule>(IotDataResRule.class);
        util.exportExcel(response, packList(list), "解析规则管理数据");
    }

    /**
     * 获取解析规则管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('device:rule:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        IotDataResRule resRule = iotDataResRuleService.getById(id);
        if(null != resRule){
            if(null != resRule.getTypeId()){
                DeviceType type = deviceTypeService.getById(resRule.getTypeId());
                if (null != type) {
                    resRule.setTypeName(type.getName());
                }
            }
            if(null != resRule.getDeviceId()){
                DeviceDevice device = deviceDeviceService.getById(resRule.getDeviceId());
                if (null != device) {
                    resRule.setDeviceName(device.getDeviceName());
                }
            }
        }
        return success(resRule);
    }

    /**
     * 新增解析规则管理
     */
    @PreAuthorize("@ss.hasPermi('device:rule:add')")
    @Log(title = "解析规则管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody IotDataResRule iotDataResRule) {
        return toAjax(iotDataResRuleService.save(iotDataResRule));
    }

    /**
     * 修改解析规则管理
     */
    @PreAuthorize("@ss.hasPermi('device:rule:edit')")
    @Log(title = "解析规则管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody IotDataResRule iotDataResRule) {
        return toAjax(iotDataResRuleService.updateById(iotDataResRule));
    }

    /**
     * 删除解析规则管理
     */
    @PreAuthorize("@ss.hasPermi('device:rule:remove')")
    @Log(title = "解析规则管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        boolean flag = iotDataResRuleService.removeByIds(new ArrayList<>(Arrays.asList(ids)));
        if(flag){
            for(Long id:ids){
                deviceRuleRefService.deleteRefByRuleId(id);
            }
        }
        return toAjax(flag);
    }

    /**
     * 获取设备测点选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        List<IotDataResRule> devices = iotDataResRuleService.list();
        return success(devices);
    }

    /**
     * 查询公共方法
     *
     * @param entity
     * @return
     */
    private LambdaQueryWrapper getWrapper(IotDataResRule entity) {
        LambdaQueryWrapper<IotDataResRule> wrapper = new LambdaQueryWrapper<>();
        if (null != entity) {
            if (StringUtils.isNotEmpty(entity.getRuleName())) {
                wrapper.like(IotDataResRule::getRuleName, entity.getRuleName());
            }
        }
        return wrapper;
    }

    /**
     * 结果封装
     *
     * @param list
     * @return
     */
    private List<IotDataResRule> packList(List<IotDataResRule> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(entity -> {
                if(null != entity.getTypeId()){
                    DeviceType type = deviceTypeService.getById(entity.getTypeId());
                    if (null != type) {
                        entity.setTypeName(type.getName());
                    }
                }
                if(null != entity.getDeviceId()){
                    DeviceDevice device = deviceDeviceService.getById(entity.getDeviceId());
                    if (null != device) {
                        entity.setDeviceName(device.getDeviceName());
                    }
                }
                if (null != entity.getDeptId()) {
                    SysDept dept = deptService.selectDeptById(entity.getDeptId());
                    if (null != dept) {
                        entity.setDeptName(dept.getDeptName());
                    }
                }
            });
        }
        return list;
    }
}
